import Vue from 'vue'
import { isObject } from '@/utils/types'

import ChangeComponent from './changeComponent/index'

/**
 * @description: 注册全局组件
 * @param {*} global
 * @return {*}
 */
export function registerGloablComponents(global) {
  const moduleKeys = Object.keys(global)
  const components = []

  // 存一下 类似 CrmRelative  的数据
  const otherObjComs = {}

  moduleKeys.forEach(moduleKey => {
    const module = global[moduleKey]
    const moduleCom = module.components || {}
    components.push(...(moduleCom.global || []))

    Object.keys(moduleCom || {}).forEach(comKey => {
      if (comKey !== 'global') {
        const coms = moduleCom[comKey]
        if (isObject(coms)) {
          const hasComs = otherObjComs[comKey] || {}
          otherObjComs[comKey] = deepMerge(hasComs, coms)
        }
      }
    })
  })
  components.forEach(com => {
    Vue.component(com.name, com)
  })

  // 处理 CrmRelative 等需要注入默认数据的组件
  ChangeComponent.injectedData(otherObjComs)
}

/**
 * @description: 合并两个对象
 * @param {*} obj1
 * @param {*} obj2
 * @return {*}
 */
function deepMerge(obj1, obj2) {
  const output = Object.assign({}, obj1)
  if (isObject(obj1) && isObject(obj2)) {
    Object.keys(obj2).forEach(key => {
      if (isObject(obj2[key])) {
        if (!(key in obj1)) { Object.assign(output, { [key]: obj2[key] }) } else { output[key] = deepMerge(obj1[key], obj2[key]) }
      } else {
        Object.assign(output, { [key]: obj2[key] })
      }
    })
  }
  return output
}
